﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Drawing.Text;
using System.Reflection;
using System.IO;

namespace PostIt.Static
{
	public static class FontCreater
	{
		[DllImport("gdi32.dll", ExactSpelling = true)]
		private static extern IntPtr AddFontMemResourceEx(byte[] pbFont, int cbFont, IntPtr pdv, out uint pcFonts);

		// Cleanup of a private font (Win2000 and later)
		[DllImport("gdi32.dll", ExactSpelling = true)]
		internal static extern bool RemoveFontMemResourceEx(IntPtr fh);

		// Some private holders of font information we are loading
		static private IntPtr _mFh = IntPtr.Zero;
		static private PrivateFontCollection _mPfc = null;


		/////////////////////////////////////
		//
		// The GetSpecialFont procedure takes a size and
		// create a font of that size using the hardcoded
		// special font name it knows about.
		//
		/////////////////////////////////////
		public static Font GetSpecialFont(string nameOfFont, float size)
		{

			Font fnt = null;

			if (null == _mPfc)
			{

				// First load the font as a memory stream
				Stream stmFont = Assembly.GetExecutingAssembly().GetManifestResourceStream(
										"PostIt.Resources." + nameOfFont);

				if (null != stmFont)
				{

					// 
					// GDI+ wants a pointer to memory, GDI wants the memory.
					// We will make them both happy.
					//

					// First read the font into a buffer
					byte[] rgbyt = new Byte[stmFont.Length];
					stmFont.Read(rgbyt, 0, rgbyt.Length);

					// Then do the unmanaged font (Windows 2000 and later)
					// The reason this works is that GDI+ will create a font object for
					// controls like the RichTextBox and this call will make sure that GDI
					// recognizes the font name, later.
					uint cFonts;
					AddFontMemResourceEx(rgbyt, rgbyt.Length, IntPtr.Zero, out cFonts);

					// Now do the managed font
					IntPtr pbyt = Marshal.AllocCoTaskMem(rgbyt.Length);
					if (null != pbyt)
					{
						Marshal.Copy(rgbyt, 0, pbyt, rgbyt.Length);
						_mPfc = new PrivateFontCollection();
						_mPfc.AddMemoryFont(pbyt, rgbyt.Length);
						Marshal.FreeCoTaskMem(pbyt);
					}
				}
			}

			if (_mPfc.Families.Length > 0)
			{
				fnt = new Font(_mPfc.Families[0], size); //skapar det!
			}

			return fnt;
		}

	}
}
